#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN MVC MODULE FOR THN WEB SERVER

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For use in commercial software, please obtain a commercial license from THN Solutions LLC.    

  + For use in free software, this library is licensed under GPL version 3. A summary of 
	GPLv3 is listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt 
	included with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 15-Apr-13 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.IO;

using Thn;
using Thn.Collections;
using Thn.Web.Mvc;
#endregion

namespace Thn.Web.Razor
{
    /// <summary>
    /// This class is responsible for rendering a Razor view.
    /// </summary>
    [ImplementContract(ContractType = typeof(IViewRenderer))]
#if DEBUG || TESTING
    public
#else
    public
#endif
 class RazorViewRenderer : IViewRenderer
    {
        #region Fields
        /// <summary>
        /// Cache of known template types by view name.
        /// </summary>
        StringDictionary<Type> mTemplates = new StringDictionary<Type>();
        #endregion

        #region Properties

        #region Path Translator
        private IPathTranslator mPathTranslator;
        /// <summary>
        /// Gets or sets the translator responsible for resolving paths.
        /// </summary>
        public IPathTranslator PathTranslator
        {
            get { return mPathTranslator; }
            set { mPathTranslator = value; }
        }
        #endregion

        #region Engine
        private RazorEngine<ViewTemplate> mEngine;
        /// <summary>
        /// Gets or sets reference to razor engine responsible for parsing & building view.
        /// </summary>
        public RazorEngine<ViewTemplate> Engine
        {
            get { return mEngine; }
            set { mEngine = value; }
        }
        #endregion

        #endregion

        #region Get View
        ViewTemplate GetView(string viewName)
        {
            ViewTemplate result;

            //look up from cache first
            Type viewType = mTemplates[viewName];

            //build type if not in cache yet
            if (viewType == null)
            {
                #region Not found in cache -> read file and compile

                //translate to local path
                string filename = mPathTranslator.Translate("/" + viewName);

                //append file extensions
                filename += ".cshtml";

                //open file
                Stream stream = null;
                Exception error = null;
                StreamReader reader = null;
                try
                {
                    //read from file
                    stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
                    reader = new StreamReader(stream);

                    //compile
                    RazorCompileArgs args = new RazorCompileArgs();
                    args.CompileToMemory = true;

#if DEBUG
                    args.GenerateCodeAsText = true;
                    RazorCompileResults compileResults = Engine.ParseAndCompileTemplate(reader, args);
                    string generatedCodes = compileResults.GeneratedCodes;
#else
                    args.GenerateCodeAsText = false;
                    RazorCompileResults compileResults = Engine.ParseAndCompileTemplate(reader, args);
#endif                    

                    //process compiled result
                    if (compileResults.IsSuccessful)
                    {
                        #region Successful

                        viewType = compileResults.CompiledType;

                        #endregion
                    }
                    else
                    {
                        #region Not successful

                        throw new Exception(compileResults.ErrorMessage);

                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    error = ex;
                }
                finally
                {
                    if (stream != null) stream.Close();
                }

                //rethrow error
                if (error != null) throw error;

                #endregion
            }

            //create result
            if (viewType != null) result = (ViewTemplate)Activator.CreateInstance(viewType);
            else result = null;

            return result;
        }
        #endregion

        #region IViewRenderer Members

        #region Render
        /// <summary>
        /// Render a specific view.
        /// </summary>
        void IViewRenderer.Render(RenderArgs args)
        {
            //get template
            ViewTemplate template = GetView(args.ViewName);

            //set model
            template.Model = args.Model;

            //set writer
            template.Writer = args.Writer;

            //execute template
            template.Execute();
        }
        #endregion

        #endregion

        #region Constructors
        /// <summary>
        /// Create a new instance.
        /// </summary>
        public RazorViewRenderer()
            : base()
        {
            mEngine = new RazorEngine<ViewTemplate>();
        }
        #endregion
    }
}
